﻿#r @"..\Microsoft.SharePoint.Client (spo)\Microsoft.SharePoint.Client.dll"
#r @"..\Microsoft.SharePoint.Client (spo)\Microsoft.SharePoint.Client.Runtime.dll"

#load "Client.fs"

open Client
open Microsoft.SharePoint.Client
open Microsoft.SharePoint.Client.Application
open System.Security;

// =======================================================
// Work with groups & users in groups and 
// =======================================================

let web = Client.Context.Web

// Create a group
let groupInfo = new GroupCreationInformation()
groupInfo.Title <- "TestGroup"
let newGroup = Client.Context.Web.SiteGroups.Add(groupInfo)
Client.ExecuteQuery()

// Display users in default owner group
let spUserColl = Client.Context.Web.AssociatedOwnerGroup.Users
Client.Load spUserColl

for spUser in spUserColl do 
    printfn "%s\n" spUser.Title

// Display all Users in all groups
let spGroups = Client.Context.Web.SiteGroups
Client.Load spGroups

for spGroup in spGroups do
    Client.Load spGroup
    let msg = spGroup.Id.ToString() + " | " + spGroup.LoginName + " | " + spGroup.Description
    printfn "%s\n" msg
    Client.Load spGroup.Users
    for spUser in spGroup.Users do
        printfn "%s\n" spUser.LoginName

// Add user to group
let usr = Client.Context.Web.EnsureUser("me@geek.onmicrosoft.com")
Client.Load usr

let members = Client.Context.Web.AssociatedMemberGroup
Client.Load members
members.Users.AddUser(usr)
Client.ExecuteQuery()

// Add a group as owner of another group
Client.Load web.AssociatedOwnerGroup
members.Owner <- web.AssociatedOwnerGroup
members.Update()
Client.ExecuteQuery()

// Display Groups in Quicklaunch
web.AllProperties.IsPropertyAvailable("vti_associategroups")
web.AllProperties.["vti_associategroups"] <- "7;6;5;22"
web.AllProperties.["vti_createdassociategroups"] <- "5;6;7"
web.Update()
Client.ExecuteQuery()

Client.Context.Web.AllProperties.["vti_associateownergroup"]